#ECCO
from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse

import requests
import json
from bs4 import BeautifulSoup



def buildingParameters(data):

    # print(data)
    #
    typeCorr = {
        "TI": "acmdlTitle:",
        "AU": "persons.authors.personName:",
        "AB:":"recordAbstract:",

    }
    logCorr = {
        "and": "AND",
        "or": "OR",
        "not": "NOT",
        "###": "###"
    }

    data["log"].append("###")

    tempStr = []
    for i in range(len(data["values"])):

        try:
            # strr = data["values"][i] + "[{}]".format(typeCorr[data["type"][i]]) + ' {} '.format(logCorr[data["log"][i]])
            strr = typeCorr[data["type"][i]] + "(" + data["values"][i] + ") {} ".format(logCorr[data["log"][i]])
            tempStr.append(strr)
        except:
            raise



    if len(tempStr) == 0:
        return -1

    strr = ''
    for value in tempStr:
        strr += value


    return strr.strip().strip("#").strip()

    # return strr.strip().strip("|").strip()

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    soup = BeautifulSoup(response.text, "html5lib")

    allData = []
    lis = soup.select("#resultsBox > ul")

    for li in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = li.select(".pic_Title > a")[0].text
        except:
            pass

        try:
            tempData["titleHref"] = li.select(".pic_Title > a")[0]["href"]
        except:
            pass

        try:
            tempData["author"] = [li.select("pic_Pub")[0].text.strip()]
        except:
            pass


        allData.append(tempData)

    return allData

def getData(cookies,keyword):

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Cache-Control': 'max-age=0',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Origin': 'http://find.galegroup.com',
        'Upgrade-Insecure-Requests': '1',
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Referer': 'http://find.galegroup.com/ecco/start.do?prodId=ECCO&userGroupName=cnruc&finalAuth=true',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    data = [
        ('inputFieldValue(0)', keyword),
        ('inputFieldName(0)', '0X'),
        ('dateIndices', 'da'),
        ('limiterFieldValue(da)', ''),
        ('standAloneLimiters', 'da'),
        ('standAloneLimiters', 'BA'),
        ('limiterFieldValue(BA)', '2NEF Or 0LRH'),
        ('limiterFieldValue(BA)', '2NEK Or 0LRL'),
        ('limiterFieldValue(BA)', '2NEI Or 0LRI'),
        ('limiterFieldValue(BA)', '2NEJ Or 0LRK'),
        ('limiterFieldValue(BA)', '2NEG Or 0LRF'),
        ('limiterFieldValue(BA)', '2NEH Or 0LRJ'),
        ('limiterFieldValue(BA)', '2NEM Or 0LRN'),
        ('limiterFieldValue(BA)', '2NEL Or 0LRM'),
        ('limiters', ''),
        ('searchType', 'BasicSearchForm'),
        ('sgHitCountType', 'None'),
        ('userGroupName', 'cnruc'),
        ('prodId', 'ECCO'),
        ('isWhatsNewAvailable', ''),
        ('TAB1', ''),
        ('TAB2', ''),
        ('ALTERNATE_TAB', ''),
        ('userGroupISBN', ''),
        ('searchResultsPerPage', '10'),
        ('method', 'doSearch'),
        ('allLimiters', 'true'),
    ]

    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }

    response = requests.post('http://find.galegroup.com/ecco/basicSearch.do', headers=headers, cookies=cookies,
                             data=data,proxies=proxies)

    allData = formData(response)


    return allData


def getOnoCookies():

    headers = {
        'Proxy-Connection': 'keep-alive',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    }

    params = (
        ('db', 'ECCO'),
    )

    s = requests.session()

    proxies = {
        "http": "http://qf:qf3.1415@202.112.118.7:10086/"
    }

    s.get('http://find.galegroup.com/itweb/cnruc', headers=headers, params=params,proxies = proxies)

    requests.cookies.RequestsCookieJar()  # 利用RequestsCookieJar获取
    cookies = s.cookies.get_dict()
    return cookies

def index(request):

    data = json.loads(request.POST.get('data', '1'))

    cookies = getOnoCookies()
    allData = getData(cookies,data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")